package com.ruoyi.app.controller;

import java.io.File;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ruoyi.app.config.AppConfig;
import com.ruoyi.app.util.circle.IsPtInPoly;
import com.ruoyi.app.util.circle.Point2D;
import com.ruoyi.common.core.utils.FileUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.app.domain.AppCostCompany;
import com.ruoyi.app.service.IAppCostCompanyService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 店铺管理Controller
 * 
 * @author ziye
 * @date 2020-07-11
 */
@RestController
@RequestMapping("/appcostcompany")
public class AppCostCompanyController extends BaseController
{
    @Autowired
    private IAppCostCompanyService appCostCompanyService;

    /**
     * 查询店铺管理列表
     */
    @PreAuthorize("@ss.hasPermi('app:appcostcompany:list')")
    @GetMapping("/list")
    public TableDataInfo list(AppCostCompany appCostCompany)
    {
        startPage();
        List<AppCostCompany> list = appCostCompanyService.selectAppCostCompanyList(appCostCompany);
        for (AppCostCompany company : list) {
            company.setCompanyPic(AppConfig.getFilepath() + company.getCompanyPic());
        }
        return getDataTable(list);
    }

    /**
     * 导出店铺管理列表
     */
    @PreAuthorize("@ss.hasPermi('app:appcostcompany:export')")
    @Log(title = "店铺管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AppCostCompany appCostCompany) throws IOException
    {
        List<AppCostCompany> list = appCostCompanyService.selectAppCostCompanyList(appCostCompany);
        ExcelUtil<AppCostCompany> util = new ExcelUtil<AppCostCompany>(AppCostCompany.class);
        util.exportExcel(response, list, "appcostcompany");
    }

    /**
     * 获取店铺管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('app:appcostcompany:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(appCostCompanyService.selectAppCostCompanyById(id));
    }

    /**
     * 新增店铺管理
     */
    @PreAuthorize("@ss.hasPermi('app:appcostcompany:add')")
    @Log(title = "店铺管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AppCostCompany appCostCompany)
    {
        appCostCompany.setState("1");
        appCostCompany.setHide(0);
        appCostCompany.setDelFlag(0);
        appCostCompany.setDeptId(0L);
        appCostCompany.setCreateId(SecurityUtils.getLoginUser().getUserId());
        appCostCompany.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        AjaxResult result = toAjax(appCostCompanyService.insertAppCostCompany(appCostCompany));
        result.put("id",appCostCompany.getId());
        result.put("state", appCostCompany.getState());
        return result;
    }

    /**
     * 修改店铺管理
     */
    @PreAuthorize("@ss.hasPermi('app:appcostcompany:edit')")
    @Log(title = "店铺管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AppCostCompany appCostCompany)
    {
        AjaxResult result = toAjax(appCostCompanyService.updateAppCostCompany(appCostCompany));
        result.put("id",appCostCompany.getId());
        result.put("state", appCostCompany.getState());
        return result;
    }

    /**
     * 删除店铺管理
     */
    @PreAuthorize("@ss.hasPermi('app:appcostcompany:remove')")
    @Log(title = "店铺管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(appCostCompanyService.deleteAppCostCompanyByIds(ids));
    }

    /**
     *  上传图片
     * http://localhost/dev-api/app/f/upload
     * 图片静态访问路径：http://localhost/dev-api/app/files/userfiles/2020/07/09/5f8204989e555f96b8689c30b1a9385d.png
     * @param picfile
     * @return
     */
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("picfile") MultipartFile picfile){
        try {

            if (!picfile.isEmpty()){
                if(picfile != null && picfile.getOriginalFilename().length()>4){
                    String picFilePath = AppConfig.getProfile();
                    String filename  = FileUtils.extractFilename("upload", picfile);
                    File file = new File(picFilePath+filename);
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    System.out.println("保存文件:"+picFilePath+filename);
                    try {
                        picfile.transferTo(file);
                        return AjaxResult.success("上传成功",filename);
                    } catch (Exception e) {
                        System.out.println("上传文件失败:"+picFilePath+filename);
                        e.printStackTrace();
                    }
                }
            }
            return AjaxResult.error("上传失败，请联系管理员");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败，请联系管理员");
        }
    }

    /**
     * 上传营业执照
     * @param picfile
     * @return
     */
    @PostMapping("/uploadLicense")
    public AjaxResult uploadLicense(@RequestParam("picfile") MultipartFile picfile){
        try {

            if (!picfile.isEmpty()){
                if(picfile != null && picfile.getOriginalFilename().length()>4){
                    String picFilePath = AppConfig.getProfile();
                    String filename  = FileUtils.extractFilename("license", picfile);
                    File file = new File(picFilePath+filename);
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }

                    System.out.println("保存文件:"+picFilePath+filename);
                    try {
                        picfile.transferTo(file);
                        return AjaxResult.success("上传成功",filename);
                    } catch (Exception e) {
                        System.out.println("上传文件失败:"+picFilePath+filename);
                        e.printStackTrace();
                    }
                }
            }
            return AjaxResult.error("上传失败，请联系管理员");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败，请联系管理员");
        }
    }

    /**
     * 查询所有店铺经纬度
     * @return
     */
    @PostMapping("/queryPointList")
    public AjaxResult queryPointList(AppCostCompany company)
    {
        List<Point2D> list = appCostCompanyService.queryPointList(company);
        return AjaxResult.success("OK", list);
    }

    @GetMapping("/queryUserList")
    public AjaxResult queryUserList()
    {
        List<Map> list = appCostCompanyService.queryUserList();
        return AjaxResult.success("OK", list);
    }

    /**
     * 更新店铺标签
     * @return
     */
    @PostMapping("/updateCompanyLable")
    public AjaxResult updateCompanyLable(@RequestBody AppCostCompany company){
        System.out.println(company.getDeptId());
        System.out.println(company.getDeptName());
        System.out.println(company.getRemark());
//        Point2D point = new Point2D(114.492576, 36.628079);
//        // 测试一个点是否在多边形内
        JSONArray pointArr = JSONArray.parseArray(company.getRemark());
        if(pointArr.size() > 0){
            List<Point2D> pts = Lists.newArrayList();
            for (int i = 0; i < pointArr.size(); i++){
                JSONObject point = pointArr.getJSONObject(i);
                pts.add(new Point2D(point.getDouble("x"), point.getDouble("y")));
            }

            AppCostCompany param = new AppCostCompany();
            //param.setDeptId(0L);
            List<Point2D> list = appCostCompanyService.queryPointList(param);
            for (Point2D point : list) {
                if(IsPtInPoly.isPtInPoly(point, pts)){
                    param.setId(point.getId());
                    param.setDeptId(company.getDeptId());
                    param.setDeptName(company.getDeptName());
                    appCostCompanyService.updatePointList(param);
                    System.out.println(point.getId() + "=" + point.getTitle());
                }
            }
        }
        return AjaxResult.success("更新成功");
    }

}
